package com.yztstudy.Controller;

import com.yztstudy.Service.AdminProductService;
import com.yztstudy.Utils.AliyunOSSUtils;
import com.yztstudy.entity.Product;
import com.yztstudy.param.ProductSaveParam;
import com.yztstudy.param.ProductSearchParam;
import com.yztstudy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 管理员调用商品服务的表示层
 */

@RestController
public class AdminProductController {

    @Autowired
    private AdminProductService adminProductService;

    @Autowired
    private AliyunOSSUtils aliyunOSSUtils;


    /**
     * TODO 商品的展示与搜索
     * @param productSearchParam 前端传过来的搜索参数
     * @return
     */
    @GetMapping("/product/list")
    public R productSearch(ProductSearchParam productSearchParam)
    {
        return adminProductService.productSearch(productSearchParam);
    }


    /**
     * TODO 上传图片
     * @param img 图片文件
     * @return
     */
    @PostMapping("/product/upload")
    public R productUpload(@RequestParam("img") MultipartFile img) throws Exception {
        // TODO 1.读取图片的信息
        String fileName = img.getOriginalFilename(); // 文件名
        fileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName;
        String contentType = img.getContentType(); // 文件类型
        byte[] content = img.getBytes(); // 图片内容(字节码形式)
        int hours = 1000; // 存储时间

        // TODO 2.上传图片至云服务器
        String url = aliyunOSSUtils.uploadImage(fileName, content, contentType, hours);
        System.out.println("图片地址: " + url);
        return R.ok("图片上传成功!", url);
    }


    /**
     * TODO 保存商品
     * @param productSaveParam 商品
     * @return
     */
    @PostMapping("/product/save")
    public R productSave(ProductSaveParam productSaveParam)
    {
        return adminProductService.productSave(productSaveParam);
    }


    /**
     * TODO 更新商品
     * @param product 商品
     * @return
     */
    @PostMapping("/product/update")
    public R productUpdate(Product product)
    {
        return adminProductService.productUpdate(product);
    }


    /**
     * TODO 删除商品
     * @param productId 商品Id
     * @return
     */
    @PostMapping("/product/remove")
    public R productRemove(Integer productId)
    {
        return adminProductService.productRemove(productId);
    }
}
